<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="渠道编号" prop="channelCode">
        <el-input v-model="queryParams.channelCode" placeholder="请输入渠道编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="渠道名称" prop="channelName" class="single-line-label">
        <span class="label-spacing"></span>
        <el-select v-readonlyRemove v-model="selectedChannelNames" multiple clearable placeholder="请选择渠道名称" filterable
          @change="updateChannelNames">
          <el-option v-for="(item, i) in extData.channelNameList || []" :key="i" :label="item.key"
            :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请选择渠道类型" filterable>
          <el-option v-for="(item, i) in extData.sourceList || []" :key="i" :label="item.key"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
          v-hasPermi="['source:baseInfo:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="baseInfoList">

      <el-table-column label="ID" align="center" prop="id" />
      <!-- <el-table-column label="渠道编号" align="center" prop="channelCode" /> -->
      <el-table-column label="渠道信息" align="center" prop="channelName" width="250">
        <template slot-scope="scope">
          <span>
            {{ scope.row.channelName }} [{{ scope.row.channelCode }}]
            <span v-if="scope.row.priceType === '2'" style="color: red;">CPS/{{ scope.row.typeRate }}</span>
          </span>
        </template>
      </el-table-column>


      <el-table-column label="类型" align="center" prop="type" />

      <el-table-column label="价格" align="center" prop="priceAmount" />
      <!-- <el-table-column label="并发量" align="center" prop="requestCountLimit" /> -->
      <el-table-column label="溢价率/起推价格" align="center" prop="priceRate">
        <template slot-scope="scope">
          {{ scope.row.priceRate }} [{{ scope.row.priceAmount * scope.row.priceRate }}]
        </template>
      </el-table-column>

       <el-table-column label="成交最低价/最高价" align="center" prop="priceRate">
        <template slot-scope="scope">
          {{ scope.row.dealMinPrice }} / {{ scope.row.dealMaxPrice }}
        </template>
      </el-table-column>

      <el-table-column label="扣量" align="center" prop="lessRate" />
      <el-table-column label="撞库/进件超时时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.checkTimeout }} / {{ scope.row.registerTimeout }}
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status === 1 ? '开' : '关' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="密钥" align="center" prop="chargeTypeStr">
        <template slot-scope="scope">
          <el-button type="text" @click="showUnionKey(scope.row)">密钥</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['source:baseInfo:edit']">修改</el-button>
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdates(scope.row)"
            v-hasPermi="['source:baseInfo:edit']">密钥</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改线索基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="渠道编号" prop="channelCode">
          <el-input v-model="form.channelCode" placeholder="请输入渠道编号" />
        </el-form-item> -->
        <el-form-item label="渠道编号" prop="channelCode">
          <el-input v-model="form.channelCode" placeholder="请输入渠道编号" />
        </el-form-item>
        <el-form-item label="价格" prop="priceAmount">
          <el-input v-model="form.priceAmount" placeholder="请输入价格" />
        </el-form-item>

        <el-form-item label="价格类型" prop="priceType">
          <el-select v-model="form.priceType" placeholder="请选择价格类型">
            <el-option label="固定价格" value="1"></el-option>
            <el-option label="分润价格" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-tooltip v-if="form.priceType === '2'" class="item" effect="dark" content="例如：28分成就填写0.8" placement="top">
          <el-form-item label="分润比率" prop="typeRate" v-if="form.priceType === '2'">
            <el-input v-model="form.typeRate" placeholder="请输入分润比率" />
          </el-form-item>
        </el-tooltip>

        <el-tooltip v-if="form.priceType === '2'" class="item" effect="dark" content="限制该线索的返回最低价格，和机构返回价格进行比较"
          placement="top">
          <el-form-item label="最低价格" prop="checkMinPrice">
            <el-input v-model.number="form.checkMinPrice" placeholder="请输入最低价格限制" type="number" :min="0" />
          </el-form-item>
        </el-tooltip>


        <el-tooltip v-if="form.priceType === '2'" class="item" effect="dark" content="当实际成交价大于成交最高价的时候，在成交最低价-成交最高价之间取值，替换实际成交价，返回给上游"
          placement="top">
          <el-form-item label="成交最低价" prop="dealMinPrice">
            <el-input v-model.number="form.dealMinPrice" placeholder="请输入成交最低价" type="number" :min="0" />
          </el-form-item>
        </el-tooltip>
        
        <el-tooltip v-if="form.priceType === '2'" class="item" effect="dark" content="当实际成交价大于成交最高价的时候，在成交最低价-成交最高价之间取值，替换实际成交价，返回给上游"
          placement="top">
          <el-form-item label="成交最高价" prop="dealMaxPrice">
            <el-input v-model.number="form.dealMaxPrice" placeholder="请输入成交最高价" type="number" :min="0" />
          </el-form-item>
        </el-tooltip>

        <el-form-item label="溢价率" prop="priceRate">
          <el-input v-model="form.priceRate" placeholder="请输入溢价率" />
        </el-form-item>
        <el-form-item label="扣量" prop="lessRate">
          <el-input v-model="form.lessRate" placeholder="请输入扣量" />
        </el-form-item>
        <el-form-item label="撞库超时时间" prop="checkTimeout">
          <el-input v-model="form.checkTimeout" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="进件超时时间" prop="registerTimeout">
          <el-input v-model="form.registerTimeout" placeholder="请输入" />
        </el-form-item>

        <!-- <el-form-item label="并发量" prop="requestCountLimit">
          <el-input v-model="form.requestCountLimit" placeholder="请输入并发量" />
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="开" value="1"></el-option>
            <el-option label="关" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回调地址" prop="callbackUrl">
          <el-input v-model="form.callbackUrl" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="opens" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择商户类型" filterable>
            <el-option v-for="(item, i) in extData.sourceList || []" :key="i" :label="item.key"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工厂类型" prop="factoryType">
          <el-input v-model="form.factoryType" />
        </el-form-item>
        <el-form-item label="apiKey" prop="apiKey">
          <el-input v-model="form.apiKey" />
        </el-form-item>
        <el-form-item label="apiSecret" prop="apiSecret">
          <el-input v-model="form.apiSecret" />
        </el-form-item>
        <el-form-item label="pubKey" prop="pubKey">
          <el-input v-model="form.pubKey" type="textarea" />
        </el-form-item>
        <el-form-item label="prikey" prop="priKey">
          <el-input v-model="form.priKey" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看联登信息-->
    <el-dialog :visible.sync="unionKeyDialogVisible" width="400px" append-to-body>
      <div class="card-container">
        <!-- <div class="dialog-content"> -->

        <div class="info-item">
          <span class="info-label">渠道名称（channelName）:</span><br>
          <span class="info-value">{{ unionKey.channelName }}</span>
        </div>

        <div class="info-item">
          <span class="info-label">渠道编号（channelCode）:</span><br>
          <span class="info-value">{{ unionKey.channelCode }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">密钥（apiSecret）:</span><br>
          <span class="info-value">{{ unionKey.apiSecret }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">接口地址（requestUrl）:</span><br>
          <span class="info-value">{{ unionKey.requestUrl }}</span>
        </div>
        <!-- </div> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { listBaseInfo, getBaseInfo, delBaseInfo, addBaseInfo, updateBaseInfo } from "@/api/source/baseInfo";
import { baseInfoExtData } from "@/api/source/baseInfo";
export default {
  name: "BaseInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      selectedChannelNames: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 线索基本信息表格数据
      baseInfoList: [],
      extData: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      opens: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channelCode: null,
        channelName: null,
        type: null,
        priceAmount: null,
        priceRate: null,
        lessRate: null,
        status: null,
        apiKey: null,
        apiSecret: null,
        pubKey: null,
        priKey: null,
        callbackUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        channelCode: [
          { required: true, message: "渠道编号不能为空", trigger: "blur" }
        ],
        channelName: [
          { required: true, message: "渠道名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        priceAmount: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        priceRate: [
          { required: true, message: "溢价率不能为空", trigger: "blur" }
        ],
        lessRate: [
          { required: true, message: "扣量不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
      },
      unionKeyDialogVisible: false,
      unionKey: {
        channelCode: '',
        channelName: '',
        apiSecret: '',
        requestUrl: process.env.VUE_APP_REQUEST_URL
      },
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    /** 查询线索基本信息列表 */
    getList() {
      this.loading = true;
      listBaseInfo(this.queryParams).then(response => {
        this.baseInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    updateChannelNames() {
      this.queryParams.channelName = this.selectedChannelNames.join(',');
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.opens = false;
      this.unionKeyDialogVisible = false;
      this.reset();
    },
    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        channelCode: null,
        channelName: null,
        
        type: null,
        priceAmount: null,
        priceRate: null,
        lessRate: null,
        status: null,
        apiKey: null,
        apiSecret: null,
        pubKey: null,
        priKey: null,
        callbackUrl: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加线索基本信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBaseInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改线索基本信息";
      });
    },
    handleUpdates(row) {
      this.reset();
      const id = row.id || this.ids
      getBaseInfo(id).then(response => {
        this.form = response.data;
        this.opens = true;
        this.title = "修改密钥";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBaseInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.opens = false;
              this.getList();
            });
          } else {
            addBaseInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除线索基本信息编号为"' + ids + '"的数据项？').then(function () {
        return delBaseInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('source/baseInfo/export', {
        ...this.queryParams
      }, `baseInfo_${new Date().getTime()}.xlsx`)
    },
    showUnionKey(row) {
      this.unionKeyDialogVisible = true;
      this.unionKey.channelCode = row.channelCode;
      this.unionKey.channelName = row.channelName;
      this.unionKey.apiSecret = row.apiSecret;
    },
  }
};
</script>
